<template>
  <!-- 面包屑导航区域 -->
  <breadcrumb :childMenu="['商品管理', '添加商品']"></breadcrumb>
  <!-- 卡片视图区域 -->
  <el-card>
    <!-- 提示区域 -->
    <el-alert
      title="添加商品信息"
      type="info"
      show-icon
      :closable="false"
      center
    ></el-alert>
    <el-steps :active="activeIndex - 0" finish-status="success" align-center>
      <el-step title="基本信息"></el-step>
      <el-step title="商品参数"></el-step>
      <el-step title="商品属性"></el-step>
      <el-step title="商品图片"></el-step>
      <el-step title="商品内容"></el-step>
      <el-step title="完成"></el-step>
    </el-steps>
    <!-- tabs区域 -->
    <el-form
      :model="addForm"
      :rules="addFormRules"
      ref="addFormRef"
      label-width="100px"
      label-position="top"
    >
      <el-tabs
        v-model="activeIndex"
        tab-position="left"
        :before-leave="beforeTabLeave"
        @tab-click="tabClicked"
      >
        <el-tab-pane label="基本信息" name="0">
          <el-form-item label="商品名称" prop="goodsName">
            <el-input v-model="addForm.goodsName"></el-input>
          </el-form-item>
          <el-form-item label="商品价格" prop="goodsPrice">
            <el-input v-model="addForm.goodsPrice" type="number"></el-input>
          </el-form-item>
          <el-form-item label="商品重量" prop="goodsWeight">
            <el-input v-model="addForm.goodsWeight" type="number"></el-input>
          </el-form-item>
          <el-form-item label="商品数量" prop="goodsNunmber">
            <el-input v-model="addForm.goodsNunmber" type="number"></el-input>
          </el-form-item>
          <el-form-item label="商品分类" prop="goodsNunmber">
            <el-cascader
              v-model="addForm.goodsCate"
              :options="cateKeyNames"
              :props="{
                expandTrigger: 'hover',
                value: 'id',
                label: 'cateName',
                children: 'children'
              }"
              @change="selectChanged"
            >
            </el-cascader>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品参数" name="1">
          <!-- 渲染表单的item项 -->
          <el-form-item
            :label="item.paramName"
            v-for="item in manyTableData"
            :key="item.id"
          >
            <el-checkbox-group v-model="item.paramValues">
              <el-checkbox
                v-for="(cb, i) in item.paramValues"
                :label="cb"
                border
              />
            </el-checkbox-group>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品属性" name="2">
          <el-form-item
            v-for="item in onlyTableData"
            :key="item.id"
            :label="item.paramName"
          >
            <el-input v-model="item.paramValues"></el-input>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品图片" name="3">
          <!-- action 表示图片要上传到后台API的地址 -->
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            list-type="picture"
            :headers="headerObj"
            :on-success="handleSuccess"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-tab-pane>
        <el-tab-pane label="商品内容" name="4">
          <!-- 使用富文本编辑器 -->
          <tinymce-editor
            id="editor"
            ref="editor"
            v-model="addForm.goodsIntroduce"
            :height="realHeight"
            @handleImgUpload="imgUpload"
            @input="inputEditNewVal"
          />
          <el-button type="primary" class="buttonAdd" @click="AddGoods"
            >添加商品</el-button
          >
        </el-tab-pane>
      </el-tabs>
    </el-form>
  </el-card>
  <!-- 图片预览 -->
  <el-dialog title="图片预览" v-model="previewVisible" width="50%">
    <img :src="previewPath" alt="" class="previewImg" />
  </el-dialog>
</template>

<script>
import Breadcrumb from "@/common/Breadcrumb.vue";
import TinymceEditor from "@/common/TinymceEditor .vue";
import { getCategoryKeyName, getCategoryAttributes } from "network/category.js";
import { addGood } from "network/goods.js";
export default {
  components: {
    Breadcrumb,
    TinymceEditor
  },
  data() {
    return {
      activeIndex: "0",
      addForm: {
        goodsName: "",
        goodsPrice: 0,
        goodsWeight: 0,
        goodsNunmber: 0,
        //商品分类
        goodsCate: [],
        //图片的路径数组
        goodsPicPaths: [],
        //商品的详情描述
        goodsIntroduce: "",
        goodsParams: []
      },
      goodsPicPath: {
        picPath: ""
      },
      //动态参数列表数据
      manyTableData: [],
      //静态属性列表数据
      onlyTableData: [],
      //级联选择器绑定的数据源
      cateKeyNames: [],
      //要上传图片的api路径
      uploadUrl: process.env.VUE_APP_API + "/upload",
      //上传文件的请求头
      headerObj: {
        Authorization: window.sessionStorage.getItem("token")
      },
      //预览的图片的路径
      previewPath: "",
      //控制预览图片弹出层的显示隐藏
      previewVisible: false,
      addFormRules: {
        goodsName: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        goodsPrice: [
          { required: true, message: "请输入商品价格", trigger: "blur" }
        ],
        goodsWeight: [
          { required: true, message: "请输入商品重量", trigger: "blur" }
        ],
        goodsNunmber: [
          { required: true, message: "请输入商品数量", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getCategoryKeyName();
  },
  computed: {
    cateId() {
      if (this.addForm.goodsCate && this.addForm.goodsCate.length === 3)
        return this.addForm.goodsCate[2];
      else return null;
    },
    realHeight() {
      return (
        (window.innerHeight ||
          document.documentElement.clientHeight ||
          document.body.clientHeight) - 300
      );
    }
  },
  methods: {
    //查询商品分类id和名称
    async getCategoryKeyName() {
      const res = await getCategoryKeyName("3");
      if (!res.success)
        return this.$message.error({ showClose: true, message: res.msg });
      this.cateKeyNames = res.response;
    },
    //级联选择器发生变化时触发
    selectChanged() {
      //证明选中的不是三级分类
      if (this.addForm.goodsCate && this.addForm.goodsCate.length !== 3) {
        this.addForm.goodsCate = [];
        return;
      }
    },
    //离开tab标签页之前触发的函数,return false将阻止标签页的切换
    //activeName:即将进入的标签页的name,oldActiveName即将离开的标签页的name
    beforeTabLeave(activeName, oldActiveName) {
      if (oldActiveName == "0" && this.addForm.goodsCate.length != 3) {
        this.$message.error({
          showClose: true,
          message: "请选择商品分类"
        });
        return false;
      }
    },
    //点击tabs标签时触发
    async tabClicked() {
      if (this.activeIndex === "1") {
        const res = await getCategoryAttributes(this.cateId, "many");
        if (!res.success)
          return this.$message.error({ showClose: true, message: res.msg });

        res.response.forEach(item => {
          item.paramValues =
            item.paramValues.length === 0 ? [] : item.paramValues.split(",");
        });
        this.manyTableData = res.response;
      } else if (this.activeIndex === "2") {
        const res = await getCategoryAttributes(this.cateId, "only");
        if (!res.success)
          return this.$message.error({ showClose: true, message: res.msg });

        res.response.forEach(item => {
          item.paramValues =
            item.paramValues.length === 0 ? [] : item.paramValues.split(",");
        });
        this.onlyTableData = res.response;
      }
    },
    //移除图片
    handleRemove(file, fileList) {
      //1.获得将要删除的图片的路径
      this.goodsPicPath.picPath = file.response.newFileName;
      var obj = JSON.parse(JSON.stringify(this.goodsPicPath));
      //2.从goodsPicPaths数组中,找到这个图片对应的索引值
      const i = this.addForm.goodsPicPaths.findIndex(
        x => x.picPath == obj.picPath
      );
      //3.调用数组的splice方法,把图片信息对象,从数组中移除
      this.addForm.goodsPicPaths.splice(i, 1);
      console.log(this.addForm.goodsPicPaths);
    },
    //预览图片
    handlePreview(file) {
      this.previewPath = file.url; //file.url 图片在服务器中的临时路径
      this.previewVisible = true;
    },
    //监听图片上传成功的事件
    handleSuccess(response) {
      this.goodsPicPath.picPath = response.newFileName;
      var obj = JSON.parse(JSON.stringify(this.goodsPicPath));
      console.log(obj);
      //将服务器返回的路径存到数组中
      this.addForm.goodsPicPaths.push(obj);
      console.log(this.addForm.goodsPicPaths);
    },
    inputEditNewVal(newValue) {
      this.addForm.goodsIntroduce = newValue;
    },
    //添加商品
    AddGoods() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error({
            showClose: true,
            message: "请填写必要的表单项"
          });
        }
        //执行添加表单的逻辑
        var obj = JSON.parse(JSON.stringify(this.addForm));
        obj.goodsCate = obj.goodsCate.join(",");
        //处理动态参数
        this.manyTableData.forEach(item => {
          const newInfo = {
            id: item.id,
            paramValues: item.paramValues.join(",")
          };
          obj.goodsParams.push(newInfo);
        });
        //处理静态属性
        this.onlyTableData.forEach(item => {
          const newInfo = {
            id: item.id,
            paramValues: item.paramValues.join(",")
          };
          obj.goodsParams.push(newInfo);
        });

        // obj.goodsPicPaths.join(",");

        //发起请求,添加商品
        //商品的名称,必须是唯一的
        const res = await addGood(obj);
        if (!res.success)
          return this.$meeage.error({ showClose: true, message: res.msg });
        this.$message.success({ showClose: true, message: "添加商品成功" });
        this.$router.push("/list");
      });
    }
  }
};
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 0 5px 0 0 !important  ;
}
.previewImg {
  width: 100%;
  height: 100%;
}
.buttonAdd {
  margin-top: 10px;
}
</style>
